package com.viaas.certification.image;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AIVirtualPlayer {
    Logger logger = Bukkit.getLogger();
    private final String name;
    private final String[] responses = {
            "真的吗？",
            "听起来很有趣！",
            "哈哈哈哈",
            "你们都在干嘛？",
            "我刚刚挖到钻石了！"
    };

    public AIVirtualPlayer(String name) {
        this.name = name;
    }

    public void respondToChat(Player player, String message) {
//        if (new Random().nextDouble() < 0.5) {  // 50% 概率 AI 回复
            Bukkit.broadcastMessage(ChatColor.GRAY + getAIResponse(player.getName(),message));
//        }
    }

    public void simulateAIChat() {
        if (new Random().nextDouble() < 0.3) {  // 30% 概率 AI 随机说话
            Bukkit.broadcastMessage(ChatColor.GRAY + name + ": " + getRandomResponse());
        }
    }

    public void toggleAIOnline() {
        if (new Random().nextDouble() < 0.5) {  // 50% 概率上下线
            Bukkit.broadcastMessage(ChatColor.YELLOW + name + " 离开了游戏");
        } else {
            Bukkit.broadcastMessage(ChatColor.YELLOW + name + " 加入了游戏");
        }
    }

    private String getAIResponse(String playerName,String message) {
        try {
            String response = HttpPostRequest.post(playerName+":"+message);
            logger.info(response);
            List<String> string = extractJson(response);
            StringBuffer stringBuffer = new StringBuffer();
            for (String s:string){
                JsonObject jsonObject = JsonParser.parseString(s).getAsJsonObject();
                String message1 = jsonObject.get("message").getAsString();
                String name = jsonObject.get("name").getAsString();
                stringBuffer.append(name+":"+message1+"\n");
            }

            // 解析 JSON 响应
            return stringBuffer.toString();

        } catch (Exception e) {
            Bukkit.getLogger().warning("无法连接 AI 服务器: " + e.getMessage());
            return "";
        }
    }

    /**
     * 提取字符串中存在的json格式字符串
     * @param text 输入的文本
     * @return 包含所有提取到的JSON字符串的列表
     */
    public static List<String> extractJson(String text) {
        if (text == null || text.isEmpty()) {
            return new ArrayList<>();
        }

        // 改进后的正则表达式，避免递归过深
        String jsonRegex = "\\{(?:[^{}\"']|\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*')*\\}";
        Pattern pattern = Pattern.compile(jsonRegex);
        Matcher matcher = pattern.matcher(text);

        List<String> jsonList = new ArrayList<>();
        while (matcher.find()) {
            jsonList.add(matcher.group());
        }
        return jsonList;
    }
    private String getRandomResponse() {
        return responses[new Random().nextInt(responses.length)];
    }
}
